<template>
  <!-- 领导带班生产记录列表 -->
  <base-breadcrumb>
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <div id="print-box" style="position: absolute; z-index: -1"></div>
      <searchData :searchData="searchOptions" @search="handleSearch" />
      <div class="page-body">
        <a-card :bordered="false">
          <!-- <title-name title="领导带班生产记录" /> -->
          <a-alert class="mb12" type="info" show-icon>
            <template slot="message">
              <span
                >
                已选择：<a>{{selectLength || 0}}</a>
                领导带班总数：<a>{{ countFrom.totalNum || 0 }}</a
                >人， 本月带班数：<a>{{ countFrom.currentMonth || 0 }}</a
                >人， 上月带班数：<a>{{ countFrom.lastMonth || 0 }}</a
                >人，
              </span>
            </template>
          </a-alert>
          <!-- <s-table
          ref="table"
          size="default"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          showPagination="auto"
        >
     
        </s-table> -->
          <list-table ref="table" class="export-table" :columns="columns" :request="loadData"  @select-click="selectClick" :isShowCountBar="false" :selectConfig="{ use: true, type: 'checkbox', rowKey: 'id' }">
            <div class="mb12" slot="prefix" slot-scope="ref">
              <a-button v-btnPermission="'hse_025_exp_05'" :loading="exportLoading[0]" icon="download" class="ml12" :disabled="!ref.selectedRowKeys.length" type="default" @click="handleExport(0, ref.selectedRowKeys)">{{
                exportLoading[0] ? '导出中' : '选中导出'
              }}</a-button>
              <!-- <a-button v-btnPermission="'qm_049_sexp_04'" :loading="exportLoading[1]" icon="cloud-download" class="ml12" type="default" @click="handleExport(1)">{{ rate[1] ? '导出中' + rate[1] : '全部导出' }}</a-button> -->
            </div>
            <template slot="replyStatusStr" slot-scope="text">
              <span style="color: red" v-if="text === '待回复'">{{ text }}</span>
              <span v-else>{{ text }}</span>
            </template>
            <template slot="operator" slot-scope="text, record">
              <MoreButton>
                <a  v-btn-permission="'hse_025_loo_04'" @click="handleUpdate('look', record)">查看</a>
                <a v-if="record.replyStatusStr === '待回复'" @click="handleUpdate('edit', record)">回复</a>
                <a v-if="record.replyStatus * 1 === 3" @click="handleUpdate('edit', record)">验收</a>
                <a  v-btn-permission="'hse_025_del_03'" @click="del(record)">删除</a>
              </MoreButton>
            </template>
          </list-table>
        </a-card>
      </div>
    </div>
  </base-breadcrumb>
</template>

<script>
import axiosApi from 'axios'
import StatusDisplay from '@/components/StatusDisplay'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'
import { STable } from '@/components'
import ThemeChoose from '@/components/themeChoose/themeChoose.vue'
import SelectCompanyAndSubCompany from '@/components/Select/SelectCompanyAndSubCompany'
import { getProductionRecordList, GetcountLeadership, produceRecordingDel,getExportHtml,downSafeTakeShiftByPdf} from '@/api/safetySupervision/safetySystem.js'
import BasePage from '@/views/basePage'
const columns = [
  { title: '带班领导', dataIndex: 'creatorName', ellipsis: true,},
  { title: '领导职务', dataIndex: 'postStrs', ellipsis: true},
  { title: '所属分公司', dataIndex: 'branchComName', ellipsis: true,},
  { title: '所属项目', dataIndex: 'projectName', ellipsis: true,},
  { title: '带班时间', dataIndex: 'leadDate', ellipsis: true,},
  { title: '完成期限', dataIndex: 'completeDate', ellipsis: true,},
  { title: '状态', dataIndex: 'replyStatusStr', scopedSlots: { customRender: 'replyStatusStr' }, ellipsis: true,width:100},
  {
    title: ' 操作',
    dataIndex: 'operator',
    scopedSlots: { customRender: 'operator' },
    width:200
  }
]

export default {
  name: 'productionRecordList' + Date.now(),
  extends: new BasePage(),
  components: {
    ThemeChoose,
    STable,
    StatusDisplay,
    SelectCompanyAndSubCompany
  },
  data() {
    this.columns = columns
    this.customColumns = columns.slice(0, 7)
    return {
      searchOptions: [
        // {
        //   name: '所属分公司',
        //   valueKey: 'branchComId',
        //   type: SelectSubCompany
        // },
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '所属项目',
        //   keyValue: 'branchComId',
        //   valueKey: 'projectId',
        //   type: SelectProject
        // },
        {
          name: '带班领导',
          value: 'takeShiftName',
          type: 'input'
        },
        {
          name: '领导所属单位',
          type: SelectCompanyAndSubCompany,
          valueKey: 'orgId'
        },
        {
          name: '领导职务',
          value: 'postStrs',
          type: 'input'
        },
        {
          name: '带班时间',
          value: 'leadTime',
          type: 'dateRange',
          attr: {
            rangeFormat: ['startTime', 'endTime']
          }
        },
        {
          name: '状态',
          value: 'replyStatus',
          type: 'select',
          data: [
            { label: '待回复', value: 0 },
            { label: '未回复', value: 1 },
            { label: '已回复', value: 2 },
            { label: '待验收', value: 3 },
            { label: '未验收', value: 4 },
            { label: '验收合格', value: 5 }
          ]
        },
        {
          name: '完成期限',
          value: 'completeDate',
          type: 'dateRange',
          attr: {
            rangeFormat: ['completeDateStart', 'completeDateEnd']
          }
        }
      ],
      formConfig: {},
      state: {
        isExpand: false
      },
      formInfo: this.$form.createForm(this, { name: 'searchForm' }),
      queryParam: {},
      countFrom: {},
      selectLength:0,
      loadData: async (parameter) => {
        this.queryParam.companyLevel = this.$currentPost().code;
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        const [err, res] = await getProductionRecordList(requestParameters)
        return new Promise((resolve, reject) => {
          if (err) {
            reject(err)
          } else {
            resolve(res)
          }
        })
      },
       exportLoading: {
        0: false,
        1: false
      }, // 导出loading
      rate: ['', ''],
    }
  },
  methods: {
    selectClick(a,b){
      this.selectLength = a.rows.length;
    },
    handleSearch(val = {}) {
      this.queryParam = {
        ...val
      }
      this.$refs.table.refresh(true)
      this.handleCount(this.queryParam)
    },
    // 处理更新操作（新增、编辑）
    handleUpdate(type, data = {}) {
      if(data.historyData*1===1){
        this.$router.push({
          name: 'UpdateProductionRecord',
          query: {
            id: data.id || '',
            pageType: type
          }
        })
      }else{
          this.$router.push({
          name: 'historyUpdateProductionRecord',
          query: {
            id: data.id || '',
            pageType: type
          }
        })
      }
    },
    //获取统计
    async handleCount(queryParam) {
      const [err, res] = await GetcountLeadership(queryParam)
      if (!err) {
        this.countFrom = res.data
      }
    },
    del(row) {
      this.$delList3(
        async (p) => {
          let [err, res] = await produceRecordingDel(p)
          if (!err) return res
          return { code: 500, data: {} }
        },
        this.$refs.table.refresh,
        { id: row.id }
      )
    },
        /**
     * @description: 导出
     * @param {*} index：导出类型：0 选中，1 全部
     * @param {*} datas：选中项
     */
    async handleExport(index, datas) {
      if(datas.length>40){
          this.$message.warning('最多导出40条数据！');
          return
      }
      this.rate[index] = '0%'
      let args = {}
      if (datas?.length) {
        args.ids = datas
      } else {
        args = this.queryParam
      }
      this.exportLoading[index] = true;
      let origin =  window.location.origin;
      let url = 'https://www.cscecxn.com:8012/',type = 0;
      if(origin==='https://pm.cscecxn.com'){
        type = 1;
      }else{
        type = 2;
      }
      let  data = await getExportHtml(args);
      let psotUrl = `${url}downSafeTakeShiftByPdfGet`;
      axiosApi.defaults.withCredentials = false;
      this.exportLoading[index] = false;
       if(data[1].code === 200){
             let req = {};
             req = data[1].data;
             req.urlStr = window.location.origin
             delete req.accessToken;
            //  let res = await  axiosApi({method:'get',url:psotUrl,data : req,responseType : 'arraybuffer',})
            let linkUrl = `${psotUrl}?fileId=${req.fileId}&fullfilename=${req.fullfilename}&type=${type}&filePrefixName=领导带班_`;
            //  window.open(linkUrl,'_blank');
             const link = document.createElement('a')
            link.style.display = 'none'
            link.href = linkUrl
            link.setAttribute('target', '_self')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.exportLoading[index] = false;
       }
         
      
    },
  },
  mounted() {
    this.handleCount(this.queryParam)
  }
}
</script>

<style lang="less" scoped>
.page-header {
  .header-row {
    display: flex;

    .flex-content {
      flex: auto;
    }

    .divider {
      margin: 0 12px;
    }

    .expand-btn {
      margin-left: 8px;
      font-size: 14px;
    }
  }
}

.page-body {
  .table-operateors {
    .ant-btn + .ant-btn {
      margin-left: 12px;
    }
  }
}
</style>